﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace AUV5.Web.Handler
{
    /// <summary>
    /// UploadAvatarHandler 的摘要说明
    /// </summary>
    public class UploadAvatarHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            string resultTip = string.Empty;  //返回信息
            bool isLogin = new PageBaseTop().IsVerified;    //是否登陆

            System.IO.Stream stream = null;
            System.Drawing.Image originalImg = null;   //原图
            System.Drawing.Image thumbImg = null;      //缩放图  

            try
            {               
                if (isLogin)
                {
                    HttpPostedFile file = context.Request.Files["Filedata"];      //上传文件      

                    string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);  //得到上传路径               

                    string lastImgUrl = @context.Request.Params["LastImgUrl"];

                    if (!string.IsNullOrEmpty(lastImgUrl))      //清除上次上传的头像
                    {
                        AUV5.Common.FileHelper.DeleteFile(HttpContext.Current.Server.MapPath(lastImgUrl));
                    }

                    if (file != null)
                    {
                        if (!System.IO.Directory.Exists(uploadPath))   //不存在上传目录则创建
                        {
                            System.IO.Directory.CreateDirectory(uploadPath);
                        }

                        string userId = new PageBaseTop().VerifiedUserID;  //用户ID                        

                        string ext = System.IO.Path.GetExtension(file.FileName).ToLower();   //上传文件的后缀（小写）

                        if (ext == ".jpg" || ext == ".png")
                        {
                            string uploadFilePath = uploadPath + userId + ext;  //上传路径

                            stream = file.InputStream;
                            originalImg = System.Drawing.Image.FromStream(stream);

                            if (originalImg.Width >= AUV5.Common.CommonDefine.avatarMinWidth && originalImg.Height >= AUV5.Common.CommonDefine.avatarMinHeight)
                            {                                
                                thumbImg = AUV5.Common.FileHelper.GetThumbNailImage(originalImg, AUV5.Common.CommonDefine.avatarMaxWidth, AUV5.Common.CommonDefine.avatarMaxHeight);  //按最大宽、高缩放

                                if (thumbImg.Width >= AUV5.Common.CommonDefine.avatarMinWidth && thumbImg.Height >= AUV5.Common.CommonDefine.avatarMinHeight)
                                {
                                    thumbImg.Save(uploadFilePath);
                                    int uploadIndex = uploadFilePath.IndexOf("UploadFile");
                                    string showPath = uploadFilePath.Substring(uploadIndex - 1).Replace('\\', '/');  //图片显示路径
                                    resultTip = showPath + "$" + thumbImg.Width + "$" + thumbImg.Height;   //返回头像路径、宽、高
                                }
                                else
                                {
                                    resultTip = "图片比例必须大于3:1";
                                }
                            }
                            else
                            {
                                resultTip = "图片尺寸必须大于" + AUV5.Common.CommonDefine.avatarMinWidth + "*" + AUV5.Common.CommonDefine.avatarMinHeight;
                            }
                        }
                    }
                    else
                    {
                        resultTip = "上传文件为空";
                    }
                }
                else
                {
                    resultTip = "未登陆";
                }
                context.Response.Write(resultTip);
            }
            catch (Exception)
            {
                context.Response.Write("上传失败");
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (thumbImg != null)
                {
                    thumbImg.Dispose();
                }
                GC.Collect();
            }           
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}